package site.wetsion.employ.server.controller;

import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import site.wetsion.employ.server.pojo.CampusNews;
import site.wetsion.employ.server.pojo.CampusNewsDetail;
import site.wetsion.employ.server.pojo.CollectionCompany;
import site.wetsion.employ.server.pojo.Company;
import site.wetsion.employ.server.pojo.CompanyDetail;
import site.wetsion.employ.server.pojo.CompanyProduct;
import site.wetsion.employ.server.pojo.Domain;
import site.wetsion.employ.server.pojo.Job;
import site.wetsion.employ.server.pojo.User;
import site.wetsion.employ.server.service.AdminService;
import site.wetsion.employ.server.service.CampusService;
import site.wetsion.employ.server.service.CompanyService;
import site.wetsion.employ.server.service.JobService;
import site.wetsion.employ.server.service.UserService;
import site.wetsion.employ.server.util.Page;
import site.wetsion.employ.server.util.Result;
import site.wetsion.employ.server.vo.CompanyProductVo;

@Controller
public class AdminController {

	@Autowired
	private UserService userService;
	@Autowired
	private AdminService adminService;
	@Autowired
	private CompanyService companyService;
	@Autowired
	private JobService jobService;
	@Autowired
	private CampusService campusService;
	
	@GetMapping("admin/login")
	public String loginPage(){
		return "admin/login";
	}
	
	@GetMapping("admin/index")
	public String index(){
		return "redirect:/admin/campus/list/1";
	}
	
	@PostMapping("admin/login")
	public String login(String email, String password, HttpServletRequest request, HttpSession session){
		User user = userService.login(email, password);
		if(user==null){
			request.setAttribute("errorMsg", "账号或密码错误！");
			return "admin/login";
		}else{
			int role = adminService.getRoleByUserId(user.getId());
			if(role == 1){
				session.setAttribute("curr_user", user);
				return "redirect:/admin/index";
			}
			request.setAttribute("errorMsg", "非后台管理员权限！");
			return "admin/login";
		}
		
	}
	
	@GetMapping("admin/enterprise_manage")
	public String enterprise_manage(Model model){
		Page page = new Page(1, 10);
		List<Company> companyList = companyService.showAllCompanyByPage(page);
		int count = companyService.getCompanyCount();
		page.setTotalRecord(count);
		model.addAttribute("companyList", companyList);
		model.addAttribute("page", page);
		List<Domain> domainList = companyService.showAllDomain();
		model.addAttribute("domainList", domainList);
		return "admin/enterprise_manage";
	}
	/**
	 * 分页显示公司
	 * @param model
	 * @param page
	 * @return
	 */
	@GetMapping("admin/enterprise_manage/{pageNum}")
	public String enterprise_manage_page(Model model, @PathVariable int pageNum){
		Page page = new Page(pageNum, 10);
		List<Company> companyList = companyService.showAllCompanyByPage(page);
		int count = companyService.getCompanyCount();
		page.setTotalRecord(count);
		model.addAttribute("companyList", companyList);
		model.addAttribute("page", page);
		List<Domain> domainList = companyService.showAllDomain();
		model.addAttribute("domainList", domainList);
		return "admin/enterprise_manage";
	}
	/**
	 * 查询公司及相关产品
	 * @param id
	 * @return
	 */
	@ResponseBody
	@GetMapping("admin/queryCompany")
	public CompanyProductVo queryCompanyById(BigInteger id){
		Company company = companyService.getCompanyById(id);
		CompanyDetail detail = companyService.getCompanyDetailById(
				company.getCompany_detail());
		CompanyProduct product = companyService.getCompanyProductByCompanyId(id);
		CompanyProductVo vo = new CompanyProductVo();
		vo.setCompany(company);
		vo.setCompanyDetail(detail);
		vo.setProduct(product);
		return vo;
	}
	
	@GetMapping("admin/addcompany")
	public String addcompanyPage(Model model){
		List<Domain> domainList = companyService.showAllDomain();
		model.addAttribute("domainList", domainList);
		return "admin/addcompany";
	}
	
	@ResponseBody
	@PostMapping("admin/addnewcompany")
	public Result addcompany(CompanyProductVo companyProductVo){
		System.out.println(companyProductVo.getCompany().toString());
		System.out.println(companyProductVo.getProduct().toString());
		companyProductVo.getCompany().setCompany_creater(new BigInteger("0"));
		boolean rs = companyService.addNewCompany(companyProductVo.getCompany(),
				companyProductVo.getProduct(), companyProductVo.getCompanyDetail());
		if(rs){
			return new Result(200, "添加成功");
		}
		return new Result(500, "添加失败");
//		return "redirect:/admin/addcompany";
	}
	/**
	 * 删除公司
	 * @param id
	 * @return
	 */
	@ResponseBody
	@GetMapping("admin/deleteCompany")
	public Result deleteCompany(BigInteger id){
		boolean rs = companyService.deleteCompany(id);
		if(rs){
			return new Result(200, "删除成功");
		}
		return new Result(400, "删除失败");
	}
	
	@ResponseBody
	@PostMapping("admin/updateCompany")
	public Result updateCompany(CompanyProductVo vo){
		Company company = vo.getCompany();
		CompanyDetail detail = vo.getCompanyDetail();
		CompanyProduct product = vo.getProduct();
		boolean rc = companyService.updateCompany(company);
		boolean rp = companyService.updateCompanyProduct(product);
		boolean rd = companyService.updateCompanyDetail(detail);
		if(!rc){
			return new Result(400, "公司基本信息修改失败！");
		}
		if(!rp){
			return new Result(400, "公司产品信息修改失败！");
		}
		if(!rd){
			return new Result(400, "公司详情信息修改失败！");
		}
		return new Result(200, "修改成功！");
	}
	
	/**
	 * 加入每日推荐
	 * @param id
	 * @return
	 */
	@ResponseBody
	@GetMapping("admin/addhotcompany")
	public Result addHotCompany(BigInteger id){
		companyService.deleteRecommedCompany();
		boolean rs = companyService.addRecommedCompany(id);
		if(rs){
			return new Result(200, "推荐成功");
		}
		return new Result(400, "推荐失败");
	}
	/**
	 * 搜索，按公司名称
	 * @param keyword
	 * @param model
	 * @return
	 */
	@GetMapping("admin/searchcompany")
	public String searchCompany(String keyword, Model model){
		if(keyword == "" || "".equals(keyword)){
			return "redirect:/admin/enterprise_manage";
		}
		Page page = new Page(1, 10);
		List<Company> companyList = companyService.searchCompanyByName(page, keyword);
		int count = companyService.getSearchCountByName(keyword);
		page.setTotalRecord(count);
		model.addAttribute("companyList", companyList);
		model.addAttribute("page", page);
		model.addAttribute("keyword", keyword);
		return "admin/enterprise_manage";
	}
	@GetMapping("admin/searchcompany/{pageNum}")
	public String searchCompanyNext(@PathVariable int pageNum, 
			String keyword, Model model){
		if(keyword == "" || "".equals(keyword)){
			return "redirect:/admin/enterprise_manage";
		}
		Page page = new Page(pageNum, 10);
		List<Company> companyList = companyService.searchCompanyByName(page, keyword);
		int count = companyService.getSearchCountByName(keyword);
		page.setTotalRecord(count);
		model.addAttribute("companyList", companyList);
		model.addAttribute("page", page);
		model.addAttribute("keyword", keyword);
		return "admin/enterprise_manage";
	}
	
	@GetMapping("admin/job_manage")
	public String job_manage(Model model){
		Page page = new Page(1, 20);
		List<Job> jobList = jobService.getAllJobByPage(page);
		int count = jobService.getJobCount();
		page.setTotalRecord(count);
		List<Domain> domainList = companyService.showAllDomain();
		model.addAttribute("domainList", domainList);
		model.addAttribute("jobList", jobList);
		model.addAttribute("page", page);
		return "admin/job_manage";
	}
	/**
	 * 分页显示职位
	 * @param model
	 * @param page
	 * @return
	 */
	@GetMapping("admin/job_manage/{pageNum}")
	public String job_manage_page(Model model, @PathVariable int pageNum){
		Page page = new Page(pageNum, 10);
		List<Job> jobList = jobService.getAllJobByPage(page);
		int count = jobService.getJobCount();
		page.setTotalRecord(count);
		model.addAttribute("jobList", jobList);
		model.addAttribute("page", page);
		List<Domain> domainList = companyService.showAllDomain();
		model.addAttribute("domainList", domainList);
		return "admin/job_manage";
	}
	@GetMapping("admin/addjob")
	public String addjobPage(Model model){
		List<Domain> domainList = companyService.showAllDomain();
		model.addAttribute("domainList", domainList);
		return "admin/addjob";
	}
	
	/**
	 * 搜索，按职位名称
	 * @param keyword
	 * @param model
	 * @return
	 */
	@GetMapping("admin/searchjob")
	public String searchJob(String keyword, Model model){
		if(keyword == "" || "".equals(keyword)){
			return "redirect:/admin/job_manage";
		}
		Page page = new Page(1, 10);
		List<Job> jobList = jobService.searchJobByName(page, keyword);
		int count = jobService.getSearchCountByName(keyword);
		page.setTotalRecord(count);
		model.addAttribute("jobList", jobList);
		model.addAttribute("page", page);
		model.addAttribute("keyword", keyword);
		return "admin/job_manage";
	}
	@GetMapping("admin/searchjob/{pageNum}")
	public String searchJobNext(@PathVariable int pageNum, 
			String keyword, Model model){
		if(keyword == "" || "".equals(keyword)){
			return "redirect:/admin/job_manage";
		}
		Page page = new Page(pageNum, 10);
		List<Job> jobList = jobService.searchJobByName(page, keyword);
		int count = jobService.getSearchCountByName(keyword);
		page.setTotalRecord(count);
		model.addAttribute("jobList", jobList);
		model.addAttribute("page", page);
		model.addAttribute("keyword", keyword);
		return "admin/job_manage";
	}
	
	@GetMapping("admin/searchuser/{pageNum}")
	public String searchUser(@PathVariable int pageNum, 
			String keyword, Model model){
		if(keyword == "" || "".equals(keyword)){
			return "redirect:/admin/forum_user_manage";
		}
		Page page = new Page(pageNum, 10);
		List<User> userList = userService.getUserListByName(keyword,page);
		int count = userService.getCountOfUserListByName(keyword);
		page.setTotalRecord(count);
		model.addAttribute("userList", userList);
		model.addAttribute("page", page);
		model.addAttribute("keyword", keyword);
		return "admin/forum_user_manage";
	}
	
	@ResponseBody
	@GetMapping("admin/setForumManager")
	public Result collectCompany(BigInteger userId, HttpSession session){
		boolean rs = userService.setUserRole(userId, 3);
		System.out.println("插入用户角色："+rs);
		if(rs){
			return new Result(200, "设置成功");
		}
		return new Result(400, "设置失败");
	}
	
	/** -----------------校园公告---------------------- */
	
	@GetMapping("admin/campus/add")
	public String addcampusPage(){
		return "admin/addCampusNews";
	}
	
	@PostMapping("admin/campus/add")
	public String addCampusNews(BigInteger id,
			BigInteger detailId,String detail_content,String news_title,
			int news_type, Model model){
		Timestamp now = new Timestamp(System.currentTimeMillis());
		CampusNews news = new CampusNews();
		news.setNews_see(0);
		news.setNews_type(news_type);
		news.setGmt_create(now);
		news.setGmt_modified(now);
		news.setNews_title(news_title);
		CampusNewsDetail detail = new CampusNewsDetail();
		detail.setDetail_content(detail_content);
		detail.setGmt_create(now);
		detail.setGmt_modified(now);
		news.setDetail(detail);
		boolean rs = campusService.insertCampusNews(news);
		if(rs){
			return "redirect:/admin/campus/list/1";
		}else{
			model.addAttribute("errorMsg", "发布失败！");
			return "admin/addCampusNews";
		}
		
	}
	@GetMapping("admin/campus/list/{pageNum}")
	public String campusList(@PathVariable int pageNum, Model model){
		Page page = new Page(pageNum, 15);
		List<CampusNews> newsList = campusService.getCampusNewsListByPage(page);
		int count  = campusService.getCountOfNews();
		page.setTotalRecord(count);
		model.addAttribute("newsList", newsList);
		model.addAttribute("page", page);
		return "admin/index";
	}
	@ResponseBody
	@GetMapping("admin/campus/del")
	public Result delCampusNews(BigInteger id){
		boolean rs = campusService.deleteCampusNewsById(id);
		if(rs){
			return new Result(200, "删除成功");
		}
		return new Result(400, "删除失败");
	}
	
	/**
	 * 修改公告
	 * @param id 公告
	 * @return 返回到公告修改页面
	 */
	@GetMapping("admin/campus/edit")
	public String editCampusNewsPage(BigInteger id, Model model){
		CampusNews campusNews = campusService.getCampusNewsById(id);
		model.addAttribute("news", campusNews);
		return "admin/addCampusNews";
	}
	@PostMapping("admin/campus/edit")
	public String editCampusNews(BigInteger id,
			BigInteger detailId,String detail_content,String news_title,
			int news_type, Model model){
		Timestamp now = new Timestamp(System.currentTimeMillis());
		CampusNews news = new CampusNews();
		news.setNews_type(news_type);
		news.setGmt_modified(now);
		news.setNews_title(news_title);
		news.setId(id);
		CampusNewsDetail detail = new CampusNewsDetail();
		detail.setDetail_content(detail_content);
		detail.setGmt_modified(now);
		detail.setId(detailId);
		news.setDetail(detail);
		boolean rs = campusService.modifyCampusNews(news);
		if(rs){
			return "redirect:/admin/campus/list/1";
		}else{
			model.addAttribute("errorMsg", "修改失败");
			return "admin/addCampusNews";
		}
	}
	
	
	@GetMapping("admin/forum_manage")
	public String forum_manage(){
		return "admin/forum_user_manage";
	}
	@GetMapping("admin/message")
	public String message(){
		return "admin/message";
	}
	
	@InitBinder("company")   
    public void initBinder1(WebDataBinder binder) {   
		binder.setFieldDefaultPrefix("company.");   
    } 
	@InitBinder("companyDetail")
	public void initBinder3(WebDataBinder binder){
		binder.setFieldDefaultPrefix("companyDetail."); 
	}
	@InitBinder("product")   
    public void initBinder2(WebDataBinder binder) {   
		binder.setFieldDefaultPrefix("product.");   
	}
	
}
